package com.qinggeng.project.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.qinggeng.common.enums.CommonEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.SecurityUtils;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.aspectj.lang.annotation.Log;
import com.qinggeng.framework.aspectj.lang.enums.BusinessType;
import com.qinggeng.framework.config.mq.MQSendUtils;
import com.qinggeng.framework.config.mq.dto.MessagePresaleDTO;
import com.qinggeng.framework.config.mq.enums.MQTypeEnum;
import com.qinggeng.framework.interceptor.annotation.RepeatSubmit;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.framework.web.page.TableDataInfo;
import com.qinggeng.project.system.domain.AttrRow;
import com.qinggeng.project.system.domain.Goods;
import com.qinggeng.project.system.domain.GoodsPresale;
import com.qinggeng.project.system.domain.json.UserCartParams;
import com.qinggeng.project.system.domain.vo.UserCartVO;
import com.qinggeng.project.system.dto.GoodsImgDTO;
import com.qinggeng.project.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 吴鹏飞
 * @date 2020/11/28
 * 预售商品
 */
@RestController
@RequestMapping("/system/goodsPresale")
@Slf4j
public class GoodsPresaleController extends BaseController {
    @Autowired
    private IGoodsPresaleService goodsPresaleService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsKeywordsService keywordsService;
    @Autowired
    private GoodsImgService goodsImgService;
    @Autowired
    private MQSendUtils mqSendUtils;
    @Autowired
    private IUserCartService userCartService;
    @Autowired
    private IAssistRecordService assistRecordService;

    /**
     * 查询商品信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Goods goods) {
        //List<Goods> list = goodsService.selectGoodsList(goods);
        goods.setDelFalg("10");
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            goods.setShopId(SecurityUtils.getShopId());
        }
        startPage();
        List<Goods> goodsSkuVoList = goodsService.selectGoodsList(goods);
        return getDataTable(goodsSkuVoList);
    }

    /**
     * 获取商品信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:query')")
    @GetMapping(value = "/{goodsId}")
    public AjaxResult getInfo(@PathVariable("goodsId") Long goodsId) {
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            Goods goods1 = goodsService.selectGoodsByIdYg(goodsId);
            if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())){
                return AjaxResult.error("只能操作自己所属商品");
            }

        }
        Goods goods = goodsService.selectGoodsByIdYg(goodsId);

        AttrRow attrRow = new AttrRow();
        attrRow.setAttributes(goods.getAttributes());
        attrRow.setGoodsPrice(goods.getGoodsPrice());
        attrRow.setGroupPrice(goods.getGroupPrice());
        attrRow.setBuyPrice(goods.getBuyPrice());
        attrRow.setLinePrice(goods.getLinePrice());
        attrRow.setGoodsName(goods.getGoodsName());
        attrRow.setGoodsImg(goods.getGoodsImg());
        attrRow.setGoodsLongImgs(goodsImgService.getSysLongImages(goodsId));
        attrRow.setGoodsMainImgs(goodsImgService.getSysMainImages(goodsId));

        List<AttrRow> attrRows = new ArrayList<>();
        attrRows.add(attrRow);
        goods.setAttrRows(attrRows);
        return AjaxResult.success(goods);
    }

    @PostMapping("/transformnNormal")
    @Log(title = "/transformnNormal普通转预售",businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @Transactional
    public AjaxResult transformnNormal(@RequestBody Goods goods){
        try {

            if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())) {
                Goods goods1 = goodsService.selectGoodsById(goods.getGoodsId());
                if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())) {
                    return AjaxResult.error("只能操作自己所属商品");
                }
            }

            List<AttrRow> attrRows = JSONArray.parseArray(JSON.toJSONString(goods.getAttrRows()), AttrRow.class);
            AttrRow attrRow = attrRows.get(0);
            goods.setAttributes(attrRow.getAttributes());
            goods.setGoodsPrice(attrRow.getGoodsPrice());
            goods.setGroupPrice(attrRow.getGroupPrice());
            goods.setLinePrice(attrRow.getLinePrice());
            goods.setBuyPrice(attrRow.getBuyPrice());
            goods.setGoodsName(attrRow.getGoodsName());
            goods.setGoodsImg(attrRow.getGoodsImg());
            goods.setGoodsType("50");
            goods.setGoodsLongImg(attrRow.getGoodsLongImg());
            Goods oldGoods=goodsService.selectGoodsById(goods.getGoodsId());
            int result = goodsService.updateGoods(goods);
            if (result != 1){
                throw new CustomException("商品修改失败");
            }
            goodsService.updateGoodsPercentage(goods);
            //正在进行中的助力商品改为助力失败
            assistRecordService.updateAssistRecordAssistSuccess(oldGoods);

            goodsImgService.deleteImages(goods.getGoodsId());
            GoodsImgDTO goodsImgDTO = new GoodsImgDTO();
            goodsImgDTO.setGoodsId(goods.getGoodsId());

            String m = attrRow.getGoodsMainImgs();
            if (StringUtils.isEmpty(m)) {
                return AjaxResult.error("主图不能为传空");
            }
            //添加多张商品主图
            String[] mainImgs = m.split(",");
            goodsImgDTO.setGoodsMainImgs(Arrays.asList(mainImgs));

            String d = goods.getListImg();
            if (StringUtils.isEmpty(m)) {
                return AjaxResult.error("详图图不能为传空");
            }

            //添加多张商品详情
            String[] detailsImgs = d.split(",");
            goodsImgDTO.setGoodstDetailsImgs(Arrays.asList(detailsImgs));
            //添加长图
            String longImg = attrRow.getGoodsLongImgs();
            if (StringUtils.isEmpty(longImg)) {
                return AjaxResult.error("长图不能为传空");
            }
            String[] longImgs = longImg.split(",");
            goodsImgDTO.setGoodstLongImgs(Arrays.asList(longImgs));
            goodsImgService.insertGoodsImgs(goodsImgDTO);

            if (goods.getPresaleId() != null){
                GoodsPresale goodsPresale = new GoodsPresale();
                goodsPresale.setId(goods.getPresaleId());
                goodsPresale.setGoodsId(goods.getGoodsId());
                goodsPresale.setLownum(goods.getLowNum());
                goodsPresale.setSpec(goods.getSpec());
                goodsPresale.setPopularity(goods.getPopularity());
                goodsPresale.setStartDate(goods.getStartDate());
                //发送异步消息
                sendPresaleAsynMessage(goods.getStartDate(),goods.getGoodsId());

                goodsPresale.setPickDate(goods.getPickDate());
                goodsPresale.setUpdateTime(new Date());
                goodsPresaleService.updateGoodsPresale(goodsPresale);
                return AjaxResult.success("转换成功");
            }

            GoodsPresale goodsPresale = new GoodsPresale();
            goodsPresale.setGoodsId(goods.getGoodsId());
            goodsPresale.setLownum(goods.getLowNum());
            goodsPresale.setSpec(goods.getSpec());
            goodsPresale.setPopularity(goods.getPopularity());
            goodsPresale.setStartDate(goods.getStartDate());
            //发送定时修改预售消息
            sendPresaleAsynMessage(goods.getStartDate(),goods.getGoodsId());

            goodsPresale.setPickDate(goods.getPickDate());
            goodsPresale.setCreateTime(new Date());
            int i = goodsPresaleService.insertGoodsPresale(goodsPresale);
            if (i != 1) {
                throw new CustomException("转换失败");
            }
            return AjaxResult.success("转换成功");

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return AjaxResult.error("系统异常", e.getMessage());
        }

    }

    /**
     * 新增预售商品
     *
     * @return
     */
    @PostMapping("/add")
    @Log(title = "add预售商品", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody Goods goods) {
        List<AttrRow> attrRows = JSONArray.parseArray(JSON.toJSONString(goods.getAttrRows()), AttrRow.class);
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())) {
            goods.setShopId(SecurityUtils.getShopId());
            goods.setAddType(CommonEnum.STATUS_20.getValue());
        }
        Long mainCategory = goodsService.selectMaxGoodsId();

        if (mainCategory == null) {

            mainCategory = 1L;
        } else {
            mainCategory += 1;
        }
        Goods goods1 = null;
        for (AttrRow attrRow : attrRows) {
            goods1 = new Goods();
            BeanUtils.copyProperties(goods, goods1);
            goods1.setAttributes(attrRow.getAttributes());
            goods1.setMainCategory(mainCategory);
            goods1.setGoodsPrice(attrRow.getGoodsPrice());
            goods1.setGroupPrice(attrRow.getGroupPrice());
            goods1.setLinePrice(attrRow.getLinePrice());
            goods1.setBuyPrice(attrRow.getBuyPrice());
            goods1.setAttributesName("规格");
            goods1.setGoodsName(attrRow.getGoodsName());
            goods1.setGoodsImg(attrRow.getGoodsImg());
            goods1.setGoodsLongImg(attrRow.getGoodsLongImg());
            int i = goodsService.insertGoods(goods1);
            goods.setGoodsId(goods1.getGoodsId());
            if (i <= 0) {
                return AjaxResult.error("新增商品失败");
            }

            //更新商品提成信息
            goodsService.updateGoodsPercentage(goods1);


            GoodsImgDTO goodsImgDTO = new GoodsImgDTO();
            goodsImgDTO.setGoodsId(goods1.getGoodsId());

            String m = attrRow.getGoodsMainImgs();
            if (StringUtils.isEmpty(m)) {
                return AjaxResult.error("主图不能为传空");
            }
            //添加多张商品主图
            String[] mainImgs = m.split(",");
            goodsImgDTO.setGoodsMainImgs(Arrays.asList(mainImgs));

            String d = goods.getListImg();
            if (StringUtils.isEmpty(m)) {
                return AjaxResult.error("详图不能为传空");
            }
            //添加多张商品详情
            String[] detailsImgs = d.split(",");
            goodsImgDTO.setGoodstDetailsImgs(Arrays.asList(detailsImgs));

            //添加长图
            String longImg = attrRow.getGoodsLongImgs();
            if (StringUtils.isEmpty(longImg)) {
                return AjaxResult.error("长图不能为传空");
            }
            String[] longImgs = longImg.split(",");

            goodsImgDTO.setGoodstLongImgs(Arrays.asList(longImgs));

            goodsImgService.insertGoodsImgs(goodsImgDTO);
        }
        GoodsPresale goodsPresale = new GoodsPresale();
        goodsPresale.setGoodsId(goods.getGoodsId());
        goodsPresale.setLownum(goods.getLowNum());
        goodsPresale.setSpec(goods.getSpec());
        goodsPresale.setPopularity(goods.getPopularity());
        goodsPresale.setStartDate(goods.getStartDate());
        //发送定时修改预售消息
        sendPresaleAsynMessage(goods.getStartDate(),goods.getGoodsId());

        goodsPresale.setPickDate(goods.getPickDate());
        goodsPresale.setCreateTime(new Date());
        int i = goodsPresaleService.insertGoodsPresale(goodsPresale);
        if (i != 1) {
            return AjaxResult.error("插入失败");
        }
        return AjaxResult.success(goods1);
    }

    private void sendPresaleAsynMessage(Date startDate,Long goodsId){
        MessagePresaleDTO messagePresaleDTO = new MessagePresaleDTO();
        messagePresaleDTO.setGoodsId(goodsId);
        messagePresaleDTO.setStartDate(startDate.getTime());
        messagePresaleDTO.setType(MQTypeEnum.PRESALE_HANDLE.getType());
        Instant instant = startDate.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        mqSendUtils.sendTimingMessage(messagePresaleDTO,localDateTime);
    }



    @PutMapping("/edit")
    @Transactional
    @Log(title = "预售商品信息", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@RequestBody Goods goods) {
        try {
            if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())) {
                Goods goods1 = goodsService.selectGoodsById(goods.getGoodsId());
                if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())) {
                    return AjaxResult.error("只能操作自己所属商品");
                }
            }
            List<AttrRow> attrRows = JSONArray.parseArray(JSON.toJSONString(goods.getAttrRows()), AttrRow.class);
            AttrRow attrRow = attrRows.get(0);
            goods.setAttributes(attrRow.getAttributes());
            goods.setGoodsPrice(attrRow.getGoodsPrice());
            goods.setGroupPrice(attrRow.getGroupPrice());
            goods.setLinePrice(attrRow.getLinePrice());
            goods.setBuyPrice(attrRow.getBuyPrice());
            goods.setGoodsName(attrRow.getGoodsName());
            goods.setGoodsImg(attrRow.getGoodsImg());
            goods.setGoodsLongImg(attrRow.getGoodsLongImg());
            goodsService.updateGoods(goods);

            //更新商品提成信息
            goodsService.updateGoodsPercentage(goods);

            goodsImgService.deleteImages(goods.getGoodsId());
            GoodsImgDTO goodsImgDTO = new GoodsImgDTO();
            goodsImgDTO.setGoodsId(goods.getGoodsId());

            String m = attrRow.getGoodsMainImgs();
            if (StringUtils.isEmpty(m)) {
                return AjaxResult.error("主图不能为传空");
            }
            //添加多张商品主图
            String[] mainImgs = m.split(",");
            goodsImgDTO.setGoodsMainImgs(Arrays.asList(mainImgs));

            String d = goods.getListImg();
            if (StringUtils.isEmpty(m)) {
                return AjaxResult.error("详图图不能为传空");
            }

            //添加多张商品详情
            String[] detailsImgs = d.split(",");
            goodsImgDTO.setGoodstDetailsImgs(Arrays.asList(detailsImgs));
            //添加长图
            String longImg = attrRow.getGoodsLongImgs();
            if (StringUtils.isEmpty(longImg)) {
                return AjaxResult.error("长图不能为传空");
            }
            String[] longImgs = longImg.split(",");
            goodsImgDTO.setGoodstLongImgs(Arrays.asList(longImgs));
            goodsImgService.insertGoodsImgs(goodsImgDTO);

            GoodsPresale goodsPresale = new GoodsPresale();
            goodsPresale.setId(goods.getPresaleId());
            goodsPresale.setGoodsId(goods.getGoodsId());
            goodsPresale.setLownum(goods.getLowNum());
            goodsPresale.setSpec(goods.getSpec());
            goodsPresale.setPopularity(goods.getPopularity());
            goodsPresale.setStartDate(goods.getStartDate());
            //发送异步消息
            sendPresaleAsynMessage(goods.getStartDate(),goods.getGoodsId());

            goodsPresale.setPickDate(goods.getPickDate());
            goodsPresale.setUpdateTime(new Date());
            goodsPresaleService.updateGoodsPresale(goodsPresale);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return AjaxResult.error("系统异常", e.getMessage());
        }

        return AjaxResult.success("修改预售商品成功");
    }

    @DeleteMapping("/delete/{goodsIds}")
    public AjaxResult delete(@PathVariable Long[] goodsIds) {
        // 进行逻辑批量删除
        for (Long goodsId : goodsIds) {
            if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())) {
                Goods goods1 = goodsService.selectGoodsById(goodsId);
                if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())) {
                    return AjaxResult.error("只能操作自己所属商品");
                }
            }
        }
        goodsService.logicalDeleteGoodsByIds(goodsIds);
        return AjaxResult.success();
    }

    @PostMapping("/changeState")
    @ResponseBody
    public AjaxResult changeState(@RequestBody Goods goods) {
        if (goods.getStatus().equals("10")){
            goods.setStatus("20");
        }else{
            goods.setStatus("10");
        }
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            Goods goods1 = goodsService.selectGoodsById(goods.getGoodsId());
            if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())){
                return AjaxResult.error("只能操作自己所属商品");
            }
        }
        return toAjax(goodsService.updateGoods(goods));
    }

    @GetMapping("/presaleCarts")
    @ResponseBody
    public TableDataInfo presaleCarts(UserCartParams userCartParams){
        Long shopId = SecurityUtils.getShopId();
        userCartParams.setShopId(shopId);
        startPage();
        List<UserCartVO> userCartVOS = userCartService.selectUserCartDtoListForPresale(userCartParams);

        return getDataTable(userCartVOS);
    }



}
